<template>
  <div>
    <div style="padding: 5px 0">
      <el-input v-model="text" @keyup.enter.native="load" style="width: 200px"> <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button @click="add" type="primary" size="mini" style="margin: 10px">新增</el-button>
      <el-button type="success" @click="exportExcel" size="mini" style="margin: 10px">导出</el-button>
    </div>
    <el-table :data="tableData" border stripe style="width: 100%" id="out-table">
      <el-table-column prop="id" label="ID" width="100" sortable> </el-table-column>
      <el-table-column prop="orderMasterNumber" label="订单编号"></el-table-column>
      <el-table-column prop="userId" label="下单人ID"></el-table-column>
      <el-table-column prop="addressMessageName" label="收货人姓名"></el-table-column>
      <el-table-column prop="addressMessagePhone" label="电话"></el-table-column>
      <el-table-column prop="addressMessageProvince" label="省"></el-table-column>
      <el-table-column prop="addressMessageCity" label="市"></el-table-column>
      <el-table-column prop="addressMessageDistrict" label="区"></el-table-column>
      <el-table-column prop="addressMessageAddress" label="详细地址"></el-table-column>
      <el-table-column prop="orderMasterMoney" label="订单金额"></el-table-column>
      <el-table-column prop="orderMasterPaymoneyMethod" label="支付方式">
        <template>
          <el-tag type="success">微信支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderMasterState" label="订单状态">
        <template slot-scope="scope">
          <el-tag v-if="!scope.row.orderMasterReceiveTime">配送中</el-tag>
          <el-tag type="success" v-else>已收货</el-tag>
        </template>
        
      </el-table-column>
      <el-table-column prop="orderMasterReceiveTime" label="收货时间" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.orderMasterReceiveTime">{{scope.row.orderMasterReceiveTime | dataFomart2}}</span>
          <span v-else><el-tag type="danger">未收货</el-tag></span>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="90">
        <template slot-scope="scope">
          {{scope.row.createTime | dataFomart2  }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="90">
        <template slot-scope="scope">
          {{scope.row.updateTime | dataFomart2}}
         </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle  @click="edit(scope.row)"></el-button>
          <el-popconfirm
              @confirm="del(scope.row.id)"
              title="确定删除？"
          >
            <el-button type="danger" icon="el-icon-delete" circle slot="reference" style="margin-left: 10px"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹窗   -->
    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" label-width="100px"
               :close-on-click-modal="false">
      <el-form :model="entity" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="订单编号" label-width="150px" prop="orderMasterNumber">
          <el-input v-model.number="entity.orderMasterNumber" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="下单人ID" label-width="150px" prop="userId">
          <el-input v-model.number="entity.userId" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="收货人姓名" label-width="150px" prop="addressMessageName">
          <el-input v-model="entity.addressMessageName" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="150px" prop="addressMessagePhone">
          <el-input v-model="entity.addressMessagePhone" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="省市区/县" prop="address"  label-width="150px">
          <el-cascader :options="cityData" v-model="address"  style="width: 80%"></el-cascader>
        </el-form-item>
         
       
        <el-form-item label="详细地址" label-width="150px" prop="addressMessageAddress">
          <el-input type="textarea" v-model="entity.addressMessageAddress" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="订单金额" label-width="150px" prop="orderMasterMoney">
          <el-input v-model="entity.orderMasterMoney" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="支付方式" label-width="150px" prop="orderMasterPaymoneyMethod">  
          <el-input v-model="entity.orderMasterPaymoneyMethod" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="订单状态" label-width="150px" prop="orderMasterState">
          <el-input v-model="entity.orderMasterState" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="收货时间" label-width="150px" prop="orderMasterReceiveTime">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="entity.orderMasterReceiveTime" style="width: 80%"></el-date-picker>
          <!-- <el-date-picker style="width: 80%" v-model="entity.orderMasterReceiveTime" type="datetime"  placeholder="选择日期时间"></el-date-picker> -->
        </el-form-item>
     

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import API from '../../utils/request'
const url = "/api/msslyyOrderMaster/"
import cityData from './citydata.js'
export default {
  name: "MsslyyOrderMaster",
  data() {
    var checkMobile = (rule, value, cb) => {
        // 验证手机号的正则表达式
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

        if (regMobile.test(value)) {
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      }
     
      var checkmoney = (rule, value, cb) => {
        // 数字或小数的正则表达式
        const regmoney = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,2})$)|^(([1-9]+)$)/

        if (regmoney.test(value)) {
          return cb()
        }

        cb(new Error('请输入正确的价格'))
      }
    return {
      address:[],
      fileList: [],
      options: [],
      text: '',
      user: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      entity: {},
      total: 0,
      cityData,
      dialogFormVisible: false,
      addFormRules:{
        orderMasterNumber:[
        { required: true, message: '请输入订单编号', trigger: 'blur' },
        { type: 'number', message: '订单编号必须为数字值'}
        ],
        userId:[
        { required: true, message: '请输入下单人ID', trigger: 'blur' },
        { type: 'number', message: '下单人ID必须为数字值'}
      
       
        ],
        address:[
        { required: true, message: '请选择省市区/县', trigger: 'blur' },
        ],
        addressMessageName:[
        { required: true, message: '请输入收货人姓名', trigger: 'blur' },
      
        ],
        addressMessagePhone:[
        { required: true, message: '请输入电话', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' },
      
        ],
        addressMessageAddress:[
        { required: true, message: '请输入详细地址', trigger: 'blur' },
      
        ],
        orderMasterMoney:[
        { required: true, message: '请输入订单金额', trigger: 'blur' },
        { validator: checkmoney, trigger: 'blur' },
      
        ],
        orderMasterPaymoneyMethod:[
        { required: true, message: '请输入支付方式', trigger: 'blur' },
      
        ],
        orderMasterState:[
        { required: true, message: '请输入订单状态', trigger: 'blur' },
      
        ],
        orderMasterReceiveTime:[
        { required: true, message: '请输入收货时间', trigger: 'blur' },
      
        ],
      
       
        
      }
    };
  },
  filters:{
    dataFomart(data){
       let dt = new Date(data);
       let y =  dt.getFullYear();
       let m = dt.getMonth()+ 1>10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>10?dt.getDate():"0"+dt.getDate(); 
       return `${y}-${m}-${d}`

       
    },
    dataFomart2(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>=10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>=10?dt.getDate():"0"+dt.getDate(); 
       let hh=dt.getHours()>=10?dt.getHours():"0"+dt.getHours();
       let mm=dt.getMinutes()>=10?dt.getMinutes():"0"+dt.getMinutes();
       let ss=dt.getSeconds()>=10?dt.getSeconds():"0"+dt.getSeconds();
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}  ${hh}:${mm}:${ss}`
    }
      },
  created() {
    this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
    this.$emit('user', this.user);
    this.load()
  },
  methods: {
    exportExcel () {
   var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
   var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
   try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.$options.name+'.xlsx')
   } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
   return wbout
  },
    fileSuccessUpload(res) {
      this.entity.file = "http://localhost:9999/files/" + res.data;
      this.fileList = [res.data]
      console.log(res)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    load() {
       API.get(url + "/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.text
          }
       }).then(res => {
          this.tableData = res.data.records || []
          this.total = res.data.total
       })
    },
    add() {
      this.address=[]
      this.entity = {}
      this.fileList = []
      this.dialogFormVisible = true
    },
    edit(obj) {
      this.entity = JSON.parse(JSON.stringify(obj))
      this.fileList = []
      this.dialogFormVisible = true
    },
    save() {
      if (this.address.length>0) {
          this.entity.addressMessageProvince=this.address[0]
        }
        if (this.address.length>=2) {
          this.entity.addressMessageCity=this.address[1]
        }
        if (this.address.length===3) {
          this.entity.addressMessageDistrict=this.address[2]
        }
      if (!this.entity.id) {
        API.post(url, this.entity).then(res => {
           if (res.code === '0') {
             this.$message({
               type: "success",
               message: "操作成功"
             })
           } else {
             this.$message({
               type: "error",
               message: res.msg
             })
           }
           this.load()
           this.dialogFormVisible = false
        })
      } else {
        API.put(url, this.entity).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "操作成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()
          this.dialogFormVisible = false
        })
      }

          

    },
    del(id) {
      API.delete(url + id).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        })
        this.load()
      })
    }
  },
};
</script>

<style scoped>
</style>
